//
//  NetworkManager.swift
//  shopAssistant
//
//  Created by 周文杰 on 16/10/12.
//  Copyright © 2016年 com.weitaming. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import SwifterSwift
import CFNetwork

typealias RequestCallback = (_ isSuccess: Bool, _ response: WTMResponse) -> Void

class NetworkManager: NSObject {
    
    public static let BASE_URL =  "http://www.yunshutech.com" //"http://192.168.0.104:8080";//
    public static let SEND_CODE = "/identifyingCodeService/getCode.action?"
    public static let REGISTER = "/identifyingCodeService/validateCode.action?"
    public static let LOGIN = "/loginService/appLogin.action?"
    public static let FORGET_PASSWORD = "/userAuthorization/updatePasswordForApp.action?"
    public static let UPLOAD_IMG = "/pictureService/uploadIcon.action?"
    public static let UPLOAD_IMG2 = "/pictureService/uploadFile.action?"
    public static let UPDATE_USER = "/userAuthorization/updateUserForApp.action?"
    public static let ZIXUN_LIST = "/infomationService/getInfomationListByType.action?"
    public static let ZIXUN_Banner = "/infomationService/getInfomationPicList.action?"
    public static let ZIXUN_Detail = "/infomationService/toInfomationContent.action?id="
    public static let ZIXUN_Love = "/infomationService/updatePraiseNum.action?"
    public static let HOMEPAGE = "/infomationService/getHomeContent.action?" //   首页信息
    public static let Kuaixun_Detail = "/newsFlashService/getNewsFlashById.action?"
    public static let Kuaixun_LIST = "/newsFlashService/getNewsFlashListForApp.action?"
    public static let Kuaixun_Channels = "/newsFlashService/getChannelListForApp.action?"
    public static let Kuaixun_Share = "/newsFlashService/toNewsFlashContent.action?"
    public static let KUAIXUN_Love =  "/newsFlashService/updatePraiseNum.action?"
    public static let TONGXUNLU_LIST = "/companyAddressListService/getCompanyAddressList.action?"
    public static let TONGXUNLU_DETAIL = "/companyAddressListService/getCompanyAddressListById.action?"
    public static let TONGXUNLU_DETAIL_PRICE = "/companyAddressListService/toPriceStrategy.action?requestType=app"
    public static let TONGXUNLU_DETAIL_PRODUCT = "/companyAddressListService/toProductContent.action?requestType=app"
    public static let XIANHUO_LIST = "/spotGoodsService/getCompanyAddressList.action?"
    public static let XIANHUO_MINE_LIST = "/spotGoodsService/getSpotGoodsListByUserId.action?"
    public static let XIANHUO_POST = "/spotGoodsService/insertSpotGoodsForApp.action?"
    public static let XIANHUO_UPDATE = "/spotGoodsService/updateSpotGoodsForApp.action?"
    public static let XIANHUO_TEMPLATE_LIST = "/spotGoodsService/getSpotGoodsTempletListByUserId.action?"
    public static let XIANHUO_TEMPLATE_ADD = "/spotGoodsService/insertSpotGoodsTempletForApp.action?"
    public static let XIANHUO_TEMPLATE_DELETE = "/spotGoodsService/deleteSpotGoodsTempletForApp.action?"
    public static let AGREEMENT = "/云数智惠APP应用软件许可及服务协议.html"
    public static let PRIVACY = "/privacy.html"

    public static let checkUpdate = "/userAuthorization/getVersion.action?";
    
    public static let Feedback = "/questionService/insertQuestion.action?";

    public static let PushChannelBind = "/userAuthorization/bindBpushChannelId.action?";
    public static let UNREGISTER = "/userAuthorization/cancelAccount.action?";

    
    static let defaultUserAgent: String = {
        //维他命导购 1.0.4 rv: 85 (iPad iPhone OS 9.0.2 zh_CN) // typical old User-Agent
        let bundle = Bundle.main
//        let infoDic = bundle.infoDictionary
//        let appName = bundle.objectForInfoDictionaryKey("CFBundleDisplayName") ?? bundle.objectForInfoDictionaryKey("CFBundleName")
        let appName = "YunshuApp" //User-Agent Do not support Chinese so far
        let marketingVersionNumber = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString")
        let developmentVersionNumber = bundle.object(forInfoDictionaryKey: "CFBundleVersion")
        
        let deviceName = UIDevice.current.model
        let OSName = UIDevice.current.systemName
        let OSVersion = UIDevice.current.systemVersion
        let locale = Locale.current.identifier
        
        let appVersion = "\(appName) \(marketingVersionNumber!) rv:\(developmentVersionNumber!) (\(deviceName) \(OSName) \(OSVersion) \(locale))"

        return appVersion
    }()
    
    static func setDefaultUserAgent() -> Void {
//        var defaultHeaders = Alamofire.SessionManager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
//        defaultHeaders["User-Agent"] = self.defaultUserAgent
//        
//        let configuration = URLSessionConfiguration.default
//        configuration.HTTPAdditionalHeaders = defaultHeaders
//        
//        let _ = Alamofire.Manager(configuration: configuration)
////        Alamofile.Manager.sharedInstance = manager
    }

    static func GET(_ subURL: String, params: [String : String]?=nil,ownerVC: UIViewController?=nil, callback:@escaping RequestCallback) -> Request {
        var urlString : String = NetworkManager.BASE_URL + subURL
        
        var params1 = params
        if !(params != nil) {
            params1 = ["requestType":"app","token":User.getToken() ?? ""]
        }else {
            params1?["requestType"] = "app"
            params1?["token"] = User.getToken() ?? ""
        }
        _ = params1?.map({ (key: String, value: String) -> String in
            urlString += key
            urlString += "="
            urlString += value
            urlString += "&"
            return urlString
        })
        
        if URL(string:urlString) == nil {
            
            urlString = NetworkManager.urlencode(urlString)
        }
        let req = AF.request(urlString, method:HTTPMethod.get, parameters:nil, encoding:URLEncoding.default, headers: nil)
            
        req.responseJSON{ (response)in

            switch response.result {
            case .success(let value):
                let json = JSON(value)
                if json["code"].int == 1 {
                    let resp = WTMResponse.init(request1: req)
                    if json["token"] != JSON.null {
                        User.setToken(json["token"].string!)
                    }
                    resp.analysis(json)
                    callback(true, resp)
                } else {
                    let resp = WTMResponse.init(request1: req)
                    self.alert(json["msg"].string!)
                    callback(false, resp)
                }
            case .failure(let error):
                let resp = WTMResponse.init(request1: req)
                let errorcode = Int32((error as NSError).code)
                
                callback(false, resp)
                if(req.response == nil && errorcode == CFNetworkErrors.cfurlErrorTimedOut.rawValue) {//超时
                    self.alert("请求超时，请检查网络设置")
                } else if(req.response == nil &&
                    (errorcode >= CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue
                        && errorcode < CFNetworkErrors.cfurlErrorTimedOut.rawValue)) {
                    self.alert("当前网络不可用，请检查网络设置")
                } else if(req.response == nil && (error as NSError).code < 0) {
                    self.alert("请求错误，请稍候重试")
                } else {
                    self.alert("服务器繁忙，请稍候重试")
                }
            }
        }
        
        return req
    }
    
    static func POST(_ subURL: String, params: [String : Any]?=nil, ownerVC: UIViewController?=nil, callback:@escaping RequestCallback) -> Request {
        
        var urlString = NetworkManager.BASE_URL + subURL + "requestType=app"
        
        if let token = User.getToken() {
            urlString = urlString + "&token=" + token
        }
        
        if URL(string:urlString) == nil {

           urlString = NetworkManager.urlencode(urlString)
        }
        
        let req: DataRequest = AF.request(urlString,
                                            method: .post,
                                            parameters: params,
                                            encoding: URLEncoding.default,
                                            headers: ["User-Agent": self.defaultUserAgent])
        req.validate().responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                if json["code"].int == 1 {
                    let resp = WTMResponse.init(request1: req)
                    if json["token"] != JSON.null {
                        User.setToken(json["token"].string!)
                    }
                    resp.analysis(json)
                    callback(true, resp)
                } else {
                    let resp = WTMResponse.init(request1: req)
                    self.alert(json["msg"].string!)
                    callback(false, resp)
                }
            case .failure(let error):
                let resp = WTMResponse.init(request1: req)
                let errorcode = Int32((error as NSError).code)
                
                callback(false, resp)
                if(req.response == nil && errorcode == CFNetworkErrors.cfurlErrorTimedOut.rawValue) {//超时
                    self.alert("请求超时，请检查网络设置")
                } else if(req.response == nil &&
                    (errorcode >= CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue
                        && errorcode < CFNetworkErrors.cfurlErrorTimedOut.rawValue)) {
                    self.alert("当前网络不可用，请检查网络设置")
                } else if(req.response == nil && (error as NSError).code < 0) {
                    self.alert("请求错误，请稍候重试")
                } else {
                    self.alert("服务器繁忙，请稍候重试")
                }
            }
     
        }
        return req
    }
    
    static func Upload(_ subURL: String, image: UIImage?=nil, ownerVC: UIViewController?=nil, callback:@escaping RequestCallback) {
        if image == nil {
            _ = NetworkManager.POST(subURL, params: nil, ownerVC: ownerVC, callback: callback)
        } else {
            var urlString = NetworkManager.BASE_URL + subURL + "requestType=app"
            if let token = User.getToken() {
                urlString = urlString + "&token=" + token
            }
            
            let req = AF.upload(multipartFormData: { multipartFormData in
                if let imageData = image!.jpegData(compressionQuality: 0.7) {
                    multipartFormData.append(imageData, withName: "img", fileName: "img.jpg", mimeType: "image/jpeg")
                }
                }, to: urlString, usingThreshold:UInt64.init(), method: .post, headers: ["User-Agent": self.defaultUserAgent])
            req.response{ response in
                    //TODO: merge with POST()
                    ////////////////////////////////////////////////////////////////////
                    switch response.result {
                    case .success(let value):
                        let json = JSON(value)
                        if let _ = json["result", "error"].string {
                            if let alert = json["result", "alert"].dictionaryObject {
                                self.showAlert(alert)
                            }
                            let resp = WTMResponse.init(request1:nil)
                            callback(false, resp)
                        } else {
                            let resp = WTMResponse.init(request1:nil)
                            resp.analysis(json)
                            callback(true, resp)
                        }
                    case .failure(let error):
                        let resp = WTMResponse.init(request1:nil)
                        let errorcode = Int32((error as NSError).code)
                        callback(false, resp)
                        if(errorcode == CFNetworkErrors.cfurlErrorTimedOut.rawValue) {//超时
                            self.alert("请求超时，请检查您的网络设置")
                        } else if((errorcode >= CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue
                            && errorcode < CFNetworkErrors.cfurlErrorTimedOut.rawValue)) {
                            self.alert("当前网络不可用，请检查您的网络设置")
                        } else if((error as NSError).code < 0) {
                            self.alert("请求错误，请稍后重试")
                        } else {
                            self.alert("服务器繁忙，请稍后重试")
                        }
                    }
            }
            
        }
    }

    static func showAlert(_ alertDic: [String : Any]) -> Void {
        if (alertDic["type"] as! String) == "notice" {
            self.alert(alertDic["message"] as! String)
        }
        
    }
    
   static func alert(_ msg: String) -> Void {
        let alert = UIAlertController(title: "错误", message:msg, preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "确定", style: UIAlertAction.Style.cancel, handler: nil))
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
        //self.presentViewController(alert, animated: true, completion: nil)
    }
    
    static func genPageInfo(page pageNo: Int, pageSize: Int) -> NSDictionary {
            return [
                "pageVar": "page",
                "pageSizeVar": "per-page",
                "currentPage": pageNo,
                "page": pageNo,
                "per-page": pageSize,
            ]
    }
    
    static func appendPagination(_ url: String, pagination: NSDictionary) -> String {
        var urlString = url
        let range = urlString.range(of: "?")
        if range == nil {
            urlString += "?"
        }
        if let page = pagination["currentPage"] as? Int {
            if let pageVer = pagination["pageVar"] as? String {
                urlString = "\(urlString)\(pageVer)=\(page+1)&"
            } else {
                urlString = "\(urlString)page=\(page+1)&"
            }
        }
        if let pageSizeVer = pagination["pageSizeVar"] as? String {
            if let pageSize = pagination[pageSizeVer] as? Int {
                urlString = "\(urlString)\(pageSizeVer)=\(pageSize)&"
            }
        }
        return urlString
    }
    static func reachesEndPage(_ pagination: NSDictionary) -> Bool {
        if let currentPage = pagination["currentPage"] as? Int {
            if let totalPage = pagination["pageCount"] as? Int {
                return currentPage >= totalPage
            }
        }
        return false
    }
    
    static func urlencode(_ originalString: String) -> String {
        let escapedString = originalString.addingPercentEncoding( withAllowedCharacters: CharacterSet.urlQueryAllowed )
        if escapedString == nil {
            return ""
        }
// swift3       let resultString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        let resultString = escapedString!
        return resultString
    }
}
